package com.lixinlei.mc.api.service;

public class UrlValidator {

    public void validate(String url) {
        String[] arr = url.split(":");

        if (arr.length == 2) { // 没有端口号，端口号默认 80
            String[] splitBySlash = url.split("/");
            String ip = splitBySlash[2];
            String port = "80";
            String path = "/" + splitBySlash[3] + "/" + splitBySlash[4];
            System.out.println();
        } else if(arr.length == 3) { // 有端口号
            String ip = arr[1].split("/")[2];
            String port = arr[2].split("/")[0];
            String path = arr[2].substring(arr[2].indexOf("/"));
            System.out.println();
        }


    }

    private String[] split(String url) {
        String[] result = new String[3];
        String[] arr = url.split(":");
        if (arr.length == 2) { // 没有端口号，端口号默认 80
            String[] splitBySlash = url.split("/");
            String ip = splitBySlash[2];
            String port = "80";
            StringBuffer path = new StringBuffer();
            for(int i = 3; i < splitBySlash.length; i++) {
                path.append("/").append(splitBySlash[i]);
            }
            result[0] = ip;
            result[1] = port;
            result[2] = path.toString();
        } else if(arr.length == 3) { // 有端口号
            String ip = arr[1].split("/")[2];
            String port = arr[2].split("/")[0];
            String path = arr[2].substring(arr[2].indexOf("/"));
            result[0] = ip;
            result[1] = port;
            result[2] = path;
        } else {
            return null;
        }
        return result;
    }

    public void splitSlash(String url) {
        String[] arr = url.split("/");
        printArr(arr);
    }

    public static void main(String[] args) {
        UrlValidator v = new UrlValidator();
//        String[] result = v.split("http://192.168.200.156:8086/library/index?name=tom&age=11");
        String[] result = v.split("http://192.168.200.156/library/book/index?name=tom&age=11");
        if (result != null && result.length == 3) {
            for (String s : result)
                System.out.println(s);
        }
    }

    private void printArr(String[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
        System.out.println("Length: " + arr.length);
    }

}
